import { isObject } from '@/utils/is';
import { useStoreCache } from '@/store';
export function routerJumpRedefine(router) {
    const routerPush = router.push;
    const routerReplace = router.replace;

    const restructure = location => {
        let name;
        function getRouteByPath(allRoutes, path): any {
            let result = '';
            for (let index = 0; index < allRoutes.length; index++) {
                const routeItem = allRoutes[index];
                if (routeItem.path == path) {
                    if (routeItem.redirect) {
                        result = getRouteByPath(allRoutes, routeItem.redirect);
                    } else {
                        result = routeItem;
                    }
                }
            }
            return result;
        }
        const allRoutes = router.getRoutes();
        if (isObject(location)) {
            if (location.name) {
                name = location.name;
            } else {
                name = getRouteByPath(allRoutes, location.path)?.name;
            }
        } else {
            getRouteByPath(allRoutes, location);
        }
        const storeCache: any = useStoreCache();
        // 点击菜单删除缓存
        storeCache.delCachedView({ name });
    };

    router.push = function push(location) {
        restructure(location);
        return routerPush.call(this, location).catch(err => err);
    };

    router.replace = function replace(location) {
        restructure(location);
        return routerReplace.call(this, location).catch(err => err);
    };
}